package org.jaronsource.sample.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import org.jaronsource.framework.core.dao.support.IGenericDao;
import org.jaronsource.framework.core.service.SearchFormSupportGenericService;
import org.jaronsource.sample.dao.SysRoleDao;
import org.jaronsource.sample.dao.SysUserDao;
import org.jaronsource.sample.domain.SysRole;
import org.jaronsource.sample.domain.SysUser;
import org.jaronsource.sample.service.SysUserService;

@Service
public class SysUserServiceImpl extends SearchFormSupportGenericService<SysUser, Integer> implements SysUserService {

	@Autowired
	private SysUserDao sysUserDao;

	@Autowired
	private SysRoleDao sysRoleDao;

	@Override
	public IGenericDao<SysUser, Integer> getDao() {
		return sysUserDao;
	}

	@Override
	@Transactional
	public void assignRole( Integer userId, Integer[] roleIds ) {
		SysUser sysUser = getDao().findReferenceByPk( userId );

		List<SysRole> roles = new ArrayList<SysRole>();
		for ( Integer roleId : roleIds ) {
			SysRole sysRole = sysRoleDao.findReferenceByPk( roleId );
			roles.add( sysRole );
		}

		sysUser.setRoles( roles );

		getDao().save( sysUser );

	}

}